<?php
/* wwwschool project

Copyright (C) 2009  Phillip Aldridge
Email : info@imi21.com
Web site http://www.imi21.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/


/**
 *  File : updateProfile.php
 *  called only via ajax 
 *  
 *  requires POST  op, id
 *  only admin and headmaster
 */  

checkSession();

$db=new WS3_Database();
$date=date("Y-m-d H:i:s");
$passwordUpdate="";

$id = $db->makeSafeInt( $_POST['id'] );
$last_name = $db->makeSafeString( $_POST['last_name'] );
$first_name = $db->makeSafeString( $_POST['first_name'] );
$email = $db->makeSafeString( $_POST['email'] );

if ( $session->userID() != $id) // something went wrong !
{
  die("Wrong user rights $id");
  exit;
}


//check for new password
//$$ TODO   Minimum and maximum string lengths etc
if ( isset($_POST['password']) && ($_POST['password']!='') ){
  $password=$db->makeSafeString( $_POST['password'] );
  $password2=$db->makeSafeString( $_POST['password2'] );
  if ( $password == $password2 ) $passwordUpdate=", `password`=MD5('$password')";
}


$q="SELECT `id`,`user_type` FROM `user` WHERE 1 AND `id`= '$id' LIMIT 1";


if ($db->query($q) && $db->nextRecord() )
{ // user does exisits
  
  
  $dbUpdate=new WS3_Database();
  
  $q="UPDATE `user` SET
  `date_modified`='$date',
  `last_name`='$last_name',
  `first_name`='$first_name',
  `email`='$email'
  $passwordUpdate
  WHERE  `id`='$id' LIMIT 1";
 
  if ($dbUpdate->query($q)){
   if (W3DEBUG) array_push($GLOBALS['W3DEBUG'],"update ok id");
  }else{
    if (W3DEBUG) array_push($GLOBALS['W3DEBUG'],"update failed id");
  }

  //$$TODO : we would need to update the session info
  //$$TODO inform the original email address of any changes
  $message="Profile updated";
}else{
  $message="Error : Profile updated ID not found";
}

  echo "document.getElementById('messages').innerHTML='$message';";
//$_POST['level']=$user_type;
//include 'listUsers.php';

?>